package com.xxxx.yebserver.controller;


import com.xxxx.yebserver.common.R;
import com.xxxx.yebserver.entity.Role;
import com.xxxx.yebserver.service.RoleService;
import com.xxxx.yebserver.vo.MenusWithRoleVo;
import com.xxxx.yebserver.vo.RoleWithMenuVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cxq
 * @since 2021-06-15
 */
@RestController
@RequestMapping("/system/basic/permiss")
public class RoleController {
    @Autowired
    RoleService roleService;


    @ApiOperation("获取所有角色信息")
    @GetMapping("/")
    public List<Role> getAllRoles(){
        return roleService.list();
    }

    @ApiOperation("获取所有角色信息和对应的菜单")
    @GetMapping("/getRoleWithMenu")
    public R getRoleWithMenu(){
        List<RoleWithMenuVo> list = roleService.getRoleWithMenu(null);
        return R.ok().data(list);
    }

    @ApiOperation("根据权限组ID获取对应的菜单ID")
    @GetMapping("/{rid}")
    public List<Long> menusWithRoleByRid(@PathVariable("rid") Long rid){
        return roleService.getRoleWithMenuById(rid);
    }


    @ApiOperation("添加角色信息")
    @PostMapping("/")
    public R addRole(@RequestBody Role role){
        if(!role.getRoleName().startsWith("ROLE_")) role.setRoleName("ROLE_"+role.getRoleName());
        boolean save = roleService.save(role);
        if(save) return R.ok();
        return R.error();
    }

    @ApiOperation("更新角色信息")
    @PutMapping("/")
    public R updateRole(@RequestBody Role role){
        if(role.getRoleName() !=null && !role.getRoleName().startsWith("ROLE_")) role.setRoleName("ROLE_"+role.getRoleName());
        boolean save = roleService.updateById(role);
        if(save) return R.ok();
        return R.error();
    }

    @ApiOperation("删除角色信息")
    @DeleteMapping("/{id}")
    public R deleteRole(@PathVariable("id") Long id){
        boolean save = roleService.removeById(id);
        if(save) return R.ok();
        return R.error();
    }

    @ApiOperation("批量删除角色信息")
    @DeleteMapping("/")
    public R deleteRoles(Long[] ids){
        boolean save = roleService.removeByIds(Arrays.asList(ids));
        if(save) return R.ok();
        return R.error();
    }
}

